#include "read_jansson.h"

#ifdef _MSC_VER
  #include <windows.h>
#endif
//-------------//
class CReadMemory {
  protected:
    pid_t pid_;
   #ifdef _MSC_VER
    HANDLE handle_;
   #endif
  public:
   #ifdef _MSC_VER
    CReadMemory(pid_t pid) : pid_(pid), handle_(0) {
      handle_ = ::OpenProcess(PROCESS_VM_READ, false, pid_);
    }
    ~CReadMemory() {
      if (handle_) ::CloseHandle(handle_);
    }
    bool read(void *addr, void *buf, size_t *size) {
      if (!handle_) return false;
      if (!addr || !buf || size <= 0) return false;
      SIZE_T sz = *size;
      auto bok = ::ReadProcessMemory(handle_, addr, buf, sizeof(void*), &sz);
      *size = sz;
      return bok;
    }
   #else
    CReadMemory(pid_t pid) : pid_(pid) {}
    bool read(void *addr, void *buf, size_t *size) {
      return false;
    }
   #endif
};
//-------------//
json_t* read_jansson(pid_t pid, void *addr) {
  if (!pid || !addr) return NULL;
  CReadMemory crm(pid);
  char buf[1024] = { 0 };
  size_t size = 16;
  if (!crm.read(addr, buf, &size)) {
    auto aa = ::GetLastError();
    return NULL;
  }
  return json_pack("{s:s}", "v", json_string(buf));
  return NULL;
}
